#!/usr/bin/env python3
"""
CAN信号发送器 (SocketCAN版本)
功能：模拟车辆信号并发送到CAN总线
"""

import can
import time
import random
import struct
import subprocess
import sys

# 定义8种车辆信号
SIGNALS = [
    {"name": "发动机转速", "id": 0x100, "min": 800, "max": 6000, "unit": "rpm"},
    {"name": "车速", "id": 0x101, "min": 0, "max": 200, "unit": "km/h"},
    {"name": "发动机温度", "id": 0x102, "min": 70, "max": 110, "unit": "°C"},
    {"name": "燃油量", "id": 0x103, "min": 0, "max": 100, "unit": "%"},
    {"name": "电池电压", "id": 0x104, "min": 11.0, "max": 14.5, "unit": "V"},
    {"name": "节气门位置", "id": 0x105, "min": 0, "max": 100, "unit": "%"},
    {"name": "制动压力", "id": 0x106, "min": 0, "max": 100, "unit": "%"},
    {"name": "转向角度", "id": 0x107, "min": -540, "max": 540, "unit": "度"},
]

def setup_vcan():
    """设置虚拟CAN接口"""
    try:
        # 创建虚拟CAN接口
        subprocess.run(['sudo', 'ip', 'link', 'add', 'vcan0', 'type', 'vcan'], 
                      capture_output=True, check=False)
        # 启动虚拟CAN接口
        subprocess.run(['sudo', 'ip', 'link', 'set', 'up', 'vcan0'], 
                      capture_output=True, check=False)
        print("✅ 虚拟CAN接口 vcan0 已创建")
        return True
    except Exception as e:
        print(f"⚠️ 无法创建虚拟CAN接口: {e}")
        return False

def main():
    print("📡 CAN信号发送器启动 (SocketCAN版本)")
    
    # 尝试设置虚拟CAN接口
    if not setup_vcan():
        print("❌ 无法设置虚拟CAN接口，请检查权限或使用其他方法")
        return
    
    try:
        # 连接到虚拟CAN通道
        bus = can.interface.Bus(interface='socketcan', channel='vcan0', bitrate=500000)
        print("✅ 已连接到虚拟CAN通道 vcan0")
        
        while True:
            for sig in SIGNALS:
                # 生成随机信号值
                value = random.uniform(sig["min"], sig["max"])
                data = struct.pack('f', value)
                
                # 创建CAN消息
                msg = can.Message(
                    arbitration_id=sig["id"], 
                    data=data, 
                    is_extended_id=False
                )
                
                # 发送消息
                try:
                    bus.send(msg)
                    print(f"📡 发送: {sig['name']} - ID:0x{sig['id']:03X}, 值:{value:.2f} {sig['unit']}")
                except can.CanError as e:
                    print(f"❌ 发送失败: {sig['name']} - {e}")
            
            time.sleep(1)  # 每秒发送一轮信号
            
    except KeyboardInterrupt:
        print("\n⏹️ 发送器已停止")
    except Exception as e:
        print(f"❌ 连接失败: {e}")
        print("💡 提示：在Linux系统上需要sudo权限来创建虚拟CAN接口")
    finally:
        try:
            bus.shutdown()
        except:
            pass

if __name__ == "__main__":
    main() 